async function fetchState() {
  const res = await fetch('/api/state');
  const data = await res.json();
  render(data);
}

function render(state) {
  const textEl = document.getElementById('chapter-text');
  const choicesEl = document.getElementById('choices');
  const varsEl = document.getElementById('vars');
  const achEl = document.getElementById('achieves');

  textEl.textContent = state.text || '';
  choicesEl.innerHTML = '';

  if (state.is_end) {
    const endTip = document.createElement('div');
    endTip.className = 'end-tip';
    endTip.textContent = '结局已达成，可选择重开或回滚。';
    choicesEl.appendChild(endTip);
  }

  (state.choices || []).forEach((c, i) => {
    const btn = document.createElement('button');
    btn.className = 'choice-btn';
    const label = document.createElement('span');
    label.className = 'choice-label';
    label.textContent = `${i + 1}. ${c.text}`;
    btn.appendChild(label);
    // 扩展入口视觉标识：文本包含“扩展”时添加徽章与样式
    const isExpansion = /扩展/.test(c.text);
    if (isExpansion) {
      btn.classList.add('expansion');
      const badge = document.createElement('span');
      badge.className = 'badge-expansion';
      badge.textContent = '扩展';
      btn.appendChild(badge);
    }
    btn.addEventListener('click', async () => {
      const res = await fetch('/api/choose', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ index: i })
      });
      const data = await res.json();
      render(data);
    });
    choicesEl.appendChild(btn);
  });

  // 工具栏
  document.getElementById('btn-rollback').onclick = async () => {
    const res = await fetch('/api/rollback', { method: 'POST' });
    const data = await res.json();
    render(data);
  };
  document.getElementById('btn-restart').onclick = async () => {
    const res = await fetch('/api/restart', { method: 'POST' });
    const data = await res.json();
    render(data);
  };

  // 状态面板
  const vars = state.vars || {};
  const varsTxt = Object.keys(vars).map(k => `${k}: ${vars[k]}`).join('  |  ');
  varsEl.innerHTML = `<b>状态</b>：${varsTxt || '（空）'}`;

  const achs = state.achievements || [];
  achEl.innerHTML = `<b>成就</b>：${achs.length ? achs.join('，') : '尚未解锁'}`;
}

fetchState();